package rjeutsky.servlets;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import rjeutsky.ControllerWrapper;
import rjeutsky.models.Subscription;
import rjeutsky.models.User;
import rjeutsky.validators.interfaces.Validator;

/**
 * Servlet implementation class NewSubscriptionServlet
 */
@WebServlet("/NewSubscription")
public class NewSubscriptionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public NewSubscriptionServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User currentUser = (User) request.getSession().getAttribute("currentUser");
		if (currentUser == null ) {
			response.sendRedirect("Login.jsp");
			return;
		}
		
		List<Long> ids = new LinkedList<Long>();
		Enumeration<String> keys = request.getParameterNames(); 
		while (keys.hasMoreElements()) {
			String key = keys.nextElement();
			if (key.startsWith("publicationId_")) {
				boolean value =  request.getParameter(key).contains("true");
				if (value) {
					key = key.replace("publicationId_", "");
					try {
						long id = Long.parseLong(key);
						ids.add(id);
					} catch (NumberFormatException ex) {
						// swallow
					}	
				}
			} 
		}
		
		if (ids.size() > 0) {
			Subscription subscription = new Subscription();
			subscription.setUserId(currentUser.getId());
			Validator<Subscription> v = ControllerWrapper.getApplicationController().getSubscriptionValidator();
			if (!v.validate(subscription)) {
				String message = URLEncoder.encode(v.getValidationErrorMessage().toString(), "UTF-8");
				response.sendRedirect("Publications.jsp?subscriptionValidation=" + message);
				return;
			}
			
			ControllerWrapper.getApplicationController().createSubscription(subscription, ids);
			response.sendRedirect("Publications.jsp?infoText=Subscription+has+been+created+successfully");
		} else {
			response.sendRedirect("Publications.jsp?subscriptionValidation=No+Values+Selected");
		}
	}

}
